package com.ruoyi.web.controller.shop;

import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.shop.domain.GoodsElement;
import com.ruoyi.shop.domain.GoodsNumLog;
import com.ruoyi.shop.service.IGoodsElementService;
import com.ruoyi.shop.service.IGoodsNumLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.shop.domain.Goods;
import com.ruoyi.shop.service.IGoodsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品信息Controller
 * 
 * @author ruoyi
 * @date 2025-08-11
 */
@Api("商品信息Controller")
@RestController
@RequestMapping("/shop/goods")
public class GoodsController extends BaseController
{
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsNumLogService goodsNumLogService;
    @Autowired
    private IGoodsElementService goodsElementService;
    /**
     * 查询商品信息列表
     */
    @ApiOperation("查询商品信息列表")
    @GetMapping("/list")
    public TableDataInfo list(Goods goods)
    {
        startPage();
        List<Goods> list = goodsService.selectGoodsList(goods);
        for (Goods goods1 : list) {
            GoodsElement goodsElement = new GoodsElement();
            goodsElement.setGoodsId(goods1.getId());
            goods1.setGoodsElements(goodsElementService.selectGoodsElementList(goodsElement));
        }
        return getDataTable(list);
    }

    /**
     * 导出商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:export')")
    @Log(title = "商品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Goods goods)
    {
        List<Goods> list = goodsService.selectGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        util.exportExcel(response, list, "商品信息数据");
    }

    /**
     * 获取商品信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(goodsService.selectGoodsById(id));
    }
    /**
     * 获取商品信息详细信息
     */
    @ApiOperation("获取商品信息详细信息")
    @GetMapping(value = "/getdetails/{id}")
    public AjaxResult getdetails(@PathVariable("id") Long id)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Goods goods = goodsService.getdetails(id,loginUser.getUserId());
        GoodsElement goodsElement = new GoodsElement();
        goodsElement.setGoodsId(goods.getId());
        goods.setGoodsElements(goodsElementService.selectGoodsElementList(goodsElement));
        return success(goods);
    }


    /**
     * 新增商品信息
     */
    @ApiOperation("新增商品信息")
    @PreAuthorize("@ss.hasPermi('shop:goods:add')")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Goods goods)
    {
        int res = goodsService.insertGoods(goods);
        for (GoodsElement goodsElement : goods.getGoodsElements()) {
            goodsElement.setGoodsId(goods.getId());
            goodsElementService.insertGoodsElement(goodsElement);
        }
        return toAjax(res);
    }

    /**
     * 修改商品信息
     */
    @ApiOperation("修改商品信息")
    @PreAuthorize("@ss.hasPermi('shop:goods:edit')")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Goods goods)
    {
        int res = goodsService.updateGoods(goods);
        goodsElementService.deleteGoodsElementByIds(goods.getGoodsElements().stream().map(GoodsElement::getId).toArray(Long[]::new));
        for (GoodsElement goodsElement : goods.getGoodsElements()) {
            goodsElement.setGoodsId(goods.getId());
            goodsElementService.insertGoodsElement(goodsElement);
        }
        return toAjax(res);
    }

    /**
     * 修改商品信息
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:edit')")
    @PutMapping(value = "/inventoryEdit")
    @Transactional
    public AjaxResult inventoryEdit(@RequestBody GoodsNumLog goodsNumLog)
    {  Goods goods = goodsService.selectGoodsById(goodsNumLog.getGoodsId());
        goodsNumLog.setGoodName(goods.getGoodName());
        goodsNumLogService.insertGoodsNumLog(goodsNumLog);
        if(goodsNumLog.getStatus().equals("1")){
//            减少
            if(goods.getInventory()<goodsNumLog.getInventory()){
                return AjaxResult.error("库存不足");
            }
            if(Objects.isNull(goods.getInventory())){
                goods.setInventory(0L);
            }
            goods.setInventory(goods.getInventory()-goodsNumLog.getInventory());
        }else{
            if(Objects.isNull(goods.getInventory())){
                goods.setInventory(0L);
            }
            goods.setInventory(goods.getInventory()+goodsNumLog.getInventory());
        }
        return toAjax(goodsService.updateGoods(goods));
    }

    /**
     * 删除商品信息
     */
    @ApiOperation("删除商品信息")
    @PreAuthorize("@ss.hasPermi('shop:goods:remove')")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(goodsService.deleteGoodsByIds(ids));
    }
}
